using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using AFI.Speargun.Web.Models;
using System.Web.Security;
using AFI.Speargun.Web.Models.Validation;
using AFI.Speargun.Web.Core;

namespace AFI.Speargun.Web.Controllers
{
    public class AssetEntryController : BaseController
    {
        //
        // GET: /AssetEntry/

        [Authorize]
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /AssetEntry/Details/{id}

        [Authorize]
        public ActionResult Details(Guid id)
        {
            var assetEntry = _service.GetAssetEntry(id);
            if (!assetEntry.CategoryReference.IsLoaded)
                assetEntry.CategoryReference.Load();

            if (!assetEntry.DepartmentReference.IsLoaded)
                assetEntry.DepartmentReference.Load();

            if (!assetEntry.AcquisitionModeReference.IsLoaded)
                assetEntry.AcquisitionModeReference.Load();

            if (!assetEntry.CurrencyReference.IsLoaded)
                assetEntry.CurrencyReference.Load();

            return View(assetEntry);
        }

        //
        // GET: /AssetEntry/Create

        [Authorize]
        public ActionResult Create()
        {
            this.BuildViewData(String.Empty, String.Empty, String.Empty);
            return View();
        }

        //
        // POST: /AssetEntry/Create

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public ActionResult Create(Guid CategoryId, Guid DepartmentId, Guid DepreciationCurrencyId, Guid AcquisitionModeId, AssetEntry assetEntry)
        {
            assetEntry.EntryCreateBy = (Guid)Membership.GetUser().ProviderUserKey;

            if (_service.CreateAssetEntry(CategoryId, DepartmentId, DepreciationCurrencyId, AcquisitionModeId, assetEntry))
                return RedirectToAction("Details", new { id = assetEntry.AssetEntryId });

            this.BuildViewData(
                assetEntry.AcquisitionMode.Appellation,
                ((DepreciationMode)assetEntry.DepreciationMode).GetTextValue(),
                assetEntry.Currency.Appellation
            );
            return View();
        }

        void BuildViewData(
            string acquisitionMode,
            string selectedDepreciationMode,
            string currency
        )
        {
            ViewData["AcquisitionModeId"] = SelectListBuilder.Create<AcquisitionMode>(_service.ListAcquisitionModes(), "AcquisitionModeId", "Appellation", acquisitionMode);
            ViewData["DepreciationMode"] = SelectListBuilder.Create(typeof(DepreciationMode), selectedDepreciationMode);
            ViewData["DepreciationCurrencyId"] = SelectListBuilder.Create<Currency>(_service.ListCurrencies(), "CurrencyId", "Appellation", currency);
        }
    }
}
